<?
include 'admin.inc.php';

check_security();

$table=$_REQUEST['table'];

/*
if($_REQUEST['action']=='savecell')
{
	$val = iconv("UTF-8","cp1251",urldecode($_REQUEST['value']));
	$val = mysql_real_escape_string($val);
	mysql_query("update $table set $_REQUEST[key]='$val' where id=$_REQUEST[id]");
	exit;
}


if($_REQUEST['action']=='delete')
{
	mysql_query("delete from $table where id=$_REQUEST[id]");
	header("Location: ?table=".$table);
	exit;
}
*/


$user_succeed=0;
$user_failed=0;
if($_REQUEST["ExecuteButton"])
{
	// выполняем скрипт
	$_REQUEST["formquery"]=stripslashes($_REQUEST["formquery"]);
	$cmds = split(";",$_REQUEST["formquery"]);
	foreach($cmds as $cmd)	
	{
		if($cmd) 
		{
			if(mysql_query($cmd))
			{
				$user_succeed++;
			}
			else
			{
				$user_failed++;
				$error_log.=mysql_error()."<br>";
			}
		}
	}
}


if($_REQUEST["AddButton"])
{
	$res = mysql_query("describe $table");
	while($row=mysql_fetch_array($res))$tablehead[] = $row[0];
	$str="insert into $table (";
	$first=true;
	for($i=1;$i<sizeof($tablehead);$i++) if($_REQUEST[$tablehead[$i]]){if(!$first)$str.=',';$str.=$tablehead[$i];$first=false;}
	$str.=") values (";
	$first=true;
	for($i=1;$i<sizeof($tablehead);$i++) if($_REQUEST[$tablehead[$i]]){if(!$first)$str.=',';$str.="'".mysql_real_escape_string($_REQUEST[$tablehead[$i]])."'";$first=false;}
	$str.=")";
	mysql_query($str);
}
$tablehead=Array();
$tabletype=Array();
$tabledata=Array();
if($_REQUEST["QueryButton"] && $_REQUEST["formquery"])
{
	// берем данный из пользовательского запроса
	$res = mysql_query($_REQUEST["formquery"]);
	$row=mysql_fetch_assoc($res);
	foreach($row as $k=>$v) $tablehead[] = $k;
	$st1 = microtime(true);
	$tabledata = DBGetRows($_REQUEST["formquery"]);
	$st2 = microtime(true);
	$st = 'Время выполнения запроса: '.($st2-$st1);
}
elseif($table)
{
	// получаем таблицу как есть
	$res = mysql_query("describe $table");
	while($row=mysql_fetch_array($res)){$tablehead[] = $row[0]; $tabletype[$row[0]] = ( is_int(strpos($row[1],'int'))?'numeric':'text'); }
	$tabledata = DBGetRows("select * from $table order by id desc limit 20");
	$countrows = ScalarSelect("select count(*) from $table");
	$extra=true;
}
?>















<style>
body{margin:0;}
a{color:blue;}
a.active{color:red;font-weight:bold;}
.error{color:red;font-weight:bold;}
img{border:0;}
</style>
<body rightmargin="0" leftmargin="0" topmargin="0" bottommargin="0">
<script>
var activecell
function GetXmlHttpObject()
{ 
	var objXMLHttp=null
	if (window.XMLHttpRequest)
	{
		objXMLHttp=new XMLHttpRequest()
	}
	else if (window.ActiveXObject)
	{
		objXMLHttp=new ActiveXObject("Microsoft.XMLHTTP")
	}
	return objXMLHttp
}
function toggle(i)
{
	document.getElementById('short'+i).style.display = (document.getElementById('short'+i).style.display==''?'none':'');
	document.getElementById('full'+i).style.display = (document.getElementById('full'+i).style.display==''?'none':'');
}
function editinplace(that,table,id,key,edittype)
{
	if(activecell) saveedit();
	activecell=that
	oldval=that.innerHTML
	window.table=table
	window.id=id
	window.key=key
	window.edittype=edittype
	if(edittype=='textarea')
	{
		h=30
		if(oldval.length>10) h = 15+oldval.length*1.4;
		that.innerHTML='<textarea id="editplace" onblur="saveedit()" style="background:#efefef;width:100%;height:'+h+'px;" name="'+key+'">'+that.innerHTML+'</textarea>';
	}
	else
		that.innerHTML='<input id="editplace" onblur="saveedit()" style="background:#efefef;width:100%;" name="'+key+'" value="'+that.innerHTML+'">';
	document.getElementById('editplace').focus();
	document.getElementById('editplace').onkeydown=kdown;
}
function saveedit()
{
	if(document.getElementById('editplace').value!=oldval)
	{
		xmlHttp=GetXmlHttpObject()
		var url="?action=savecell&table="+window.table+"&id="+window.id+"&key="+window.key+"&value="+encodeURI(document.getElementById('editplace').value)
		xmlHttp.open("GET",url,true)
		xmlHttp.send(null)
	}
	
	activecell.innerHTML=document.getElementById('editplace').value;
	activecell=null
}
function canceledit()
{
	activecell.innerHTML=oldval;
	activecell=null
}
function kdown(k)
{
	if (k)
		 {
          ctrl=k.ctrlKey;
          k=k.which;
         }
         else
         {
          k=event.keyCode;
          ctrl=event.ctrlKey;
         }
if(k==27) canceledit();
if(k==13 && ctrl) saveedit();
else if(window.edittype!='textarea' && k==13) saveedit();

}
</script>
<table width="100%" height="100%">
<tr>
<td width="190" valign="top" bgcolor="#efefef">
<a href="?formquery=show+full+processlist&QueryButton=1">processlist</a>
<br>
<a href="?formquery=show+table+status&QueryButton=1">tables</a>
<br>
<hr>
Tables:
<br>
<?
	$res = mysql_query("show tables");
	while($row=mysql_fetch_array($res))
	{
		if($table==$row[0])
		{
		?>
		<a href="?table=<?=$row[0]?>" class="active"><?=$row[0]?></a><br>
		<?
		}		else      {
		?>
		<a href="?table=<?=$row[0]?>"><?=$row[0]?></a><br>
		<?}
	}
?>
<br>
<br>
</td>








<td valign="top">
<table>
<form method="post">
<tr><td>
<textarea name="formquery" style="width:700px; height:150px;font-size:12px;"><?=$_REQUEST["formquery"]?></textarea>
</td>
<td>
<input type="Submit" name="ExecuteButton" value="Execute script" style="width:110px;">
<br>
<input type="Submit" name="QueryButton" value="Query data" style="width:110px;">
</td></tr>
</form>
</table>
<br>

<?if ($countrows>0){?>
Count: <?=$countrows?>
<br><br>
<? } ?>

<table border="1">
<tr bgcolor="#c0c0c0">
<?
// отрисовка таблицы
foreach($tablehead as $th) echo '<td>'.$th.'</td>';
if($extra)echo '<td>Действия</td>';
?>
<?
if($extra)
{
// поле для новой строки
echo '<tr><form method="post">';
foreach($tablehead as $th) if($th!='id') echo '<td><input type="Text" style="width:100%" name="'.$th.'"></td>'; else echo '<td>*</td>';
echo '<td><input type="Submit" name="AddButton" value="Добавить"></td>';
echo '</form></tr>';
}
?>
<?
$i=0;
foreach($tabledata as $td){
	echo '<tr>';
	foreach($tablehead as $th)
	{
		$str = $td[$th];
		$str = str_replace('<','&lt;',$str);
		$str = str_replace('<','&gt;',$str);
		if(strlen($str)>10000)
		{
			$res = "<div id='short{$i}'>".substr($str,0,200)."...<a href='javascript:toggle({$i})'>раскрыть</a></div>";
			$res.= "<div id='full{$i}' style='display:none;'>".$str." <a href='javascript:toggle({$i})'>свернуть</a></div>";
			$str=$res;
		}
		$edittype='textarea';
		if($tabletype[$th]=='numeric') $edittype='input';
		
		if($th=='dt' || $th=='create_date')
		{
			echo '<td>'.$str.' ('.date('d-m-Y G:i',$str).')</td>';
		}
		else
		{
		echo '<td unselectable=on';
		if(0 && strlen($str)<=200) echo  ' onclick="editinplace(this,\''.$table.'\',\''.$td['id'].'\',\''.$th.'\',\''.$edittype.'\')"';
		echo  '>'.$str.'</td>';
		}
		
	}
	if($extra){
		echo '<td><a href="?table='.$table.'&action=delete&id='.$td['id'].'" onclick="return confirm(\'Вы уверены?\')"><img src="/skins/admin/default/images/cancel.gif"></a></td>';
	}
	echo '</tr>';
	$i++;
}
?>
</table>
	
	<br>
	<br>
	<?=$st?>

</td>








</tr>
</table>